#coding=utf-8
from PyQt5.QtWidgets import QApplication,QWidget,QMessageBox,QFileDialog
from PyQt5.QtGui import QPixmap,QImage
import sys
import re

'''
todolist:
1、配置文件是否存在检测cfg.ini
2、requests加入。获取手机号码
3、adb尝试获取手表环境
'''
from win32api import ShellExecute
from dependence.my_log import MyLoger
from dependence.design import Ui_Form
from dependence.my_cmd import cmd_run,cmd_run_show_no_return,cmd_run_show_with_return
from dependence.my_watch import XTCWatch

cfg_ini = "dependence/cfg.ini"

class MainWindows(QWidget,Ui_Form):
    def __init__(self):
        super(MainWindows, self).__init__()
        self.mylog = MyLoger().get_logger(__name__)##日志初始化
        self.setupUi(self)##ui设置
        self.app_init()##应用初始化

    def app_init(self):
        '''
        应用初始化，槽信号配置
        :return:
        '''
        self.Watch = XTCWatch()#实例化
        self.readcbx()#从配置文件钟读取列表
        self.BatAdd_BTN.clicked.connect(self.file_addpath)#增加脚本
        self.BatDelete_BTN.clicked.connect(lambda :self.file_removepath(self.file_cbx.currentText()))#删除脚本
        self.BatExecute_BTN.clicked.connect(lambda : self.file_softlaunch(self.file_cbx.currentText()))#执行脚本

        self.DeviceOn_BTN.clicked.connect(self.watch_detected)#设备检测按键
        self.DialActivity_BTN.clicked.connect(self.open_watch_dial_ui)#启动拨号界面
        self.ConfigActivity_BTN.clicked.connect(self.open_change_env_ui)  # 启动环境切换界面
        self.DebugActivity_BTN.clicked.connect(self.open_adb_ui)  # 启动adb界面
        self.ControllerActivity_BTN.clicked.connect(self.open_selfcheck_ui)  # 启动自检界面
        self.Reboot_BTN.clicked.connect(self.watch_reboot)  # 重启手表
        self.Reboot_edlBTN.clicked.connect(self.watch_reboot_edl)  # 强制重启手表
        self.get_launcher_BTN.clicked.connect(self.get_watch_launcher)  # 获取手表launcher
        self.get_battery_BTN.clicked.connect(self.get_watch_battery)  # 获取手表电量信息
        self.get_prop_BTN.clicked.connect(self.get_watch_prop)  # 获取手表电量信息
        self.Excute_Cmd_Button.clicked.connect(lambda :self.excute_input_cmd(self.Cmd_Output_LE.text()))  # 执行输入命令

    def readcbx(self):
        '''
        从配置文件钟读取列表
        :return:
        '''
        self.file_cbx.clear()
        with open(cfg_ini, "r") as f:
            self.context = f.read()
            self.pathdict = eval(self.context)#执行一个字符串表达式，并返回表达式的值。
            for k in self.pathdict.keys():
                self.file_cbx.addItem(k)

    def file_readcbx(self):
        '''
        从配置文件钟读取列表
        :return:
        '''
        self.file_cbx.clear()
        with open(cfg_ini, "r") as f:
            self.context = f.read()
            self.pathdict = eval(self.context)#执行一个字符串表达式，并返回表达式的值。
            for k in self.pathdict.keys():
                self.file_cbx.addItem(k)

    def file_removepath(self,soft_path):
        '''
        删除路径
        :param soft_path: 程序路径
        :return:
        '''
        reply = QMessageBox.warning(self,"Warnning",
                                         self.tr("是否删除该路径？"),
                                         QMessageBox.Yes|QMessageBox.No,
                                         QMessageBox.No)

        if reply == QMessageBox.Yes and self.pathdict != {}:
            self.pathdict.pop(soft_path)
            with open(cfg_ini, 'w') as f:
                f.write(str(self.pathdict))
            self.readcbx()

    def file_addpath(self):
        '''
        增加应用路径
        :return:
        '''
        filename = QFileDialog.getOpenFileName(self,caption="选择应用")
        if filename[0] != '':
            self.pathdict[filename[0]] = filename[0]
            self.file_cbx.clear()
            for k in self.pathdict.keys():
                self.file_cbx.addItem(k)
        with open(cfg_ini,'w') as f:
            f.write(str(self.pathdict))

    def file_softlaunch(self, soft_path):
        '''
        启动路径程序
        :param soft_path:程序路径
        :return:
        '''
        ShellExecute(0, "open", soft_path, "", "", 1)  # win32调用软件启动def

    def watch_detected(self):
        '''
        手表检测，获取相关信息并生成二维码
        :return:
        '''
        ##清空文本框
        self.serialnum_LE.clear()
        self.Bind_LE.clear()
        self.WatchType_LE.clear()
        self.WatchModule_LE.clear()
        self.Platform_LE.clear()
        ##设备检测
        try:
            command = "adb devices"
            res_str = cmd_run(command)
            cmd_run_show_with_return(control=self.result_TE, show_msg="检测手表 ", command=command)
            serialnum = ''
            try:
                serialnum = re.findall(r"(.*?)	",res_str)[0]
            except Exception:
                self.label1.setText("未获取到设备")
            if serialnum != '':
                self.mylog.debug("获取设备 "+serialnum)
                self.Watch.serialnum = serialnum
                self.Watch.get_watch_param()# 获取手表基础参数
                self.Watch.make_qrode()  # 生成二维码
                self.label1.setPixmap(QPixmap.fromImage(QImage("dependence/绑定二维码.png")))#显示二维码
                self.serialnum_LE.setText(self.Watch.serialnum)
                self.Bind_LE.setText(self.Watch.bindnum)
                self.WatchType_LE.setText(self.Watch.module)
                self.WatchModule_LE.setText(self.Watch.name)
                self.Platform_LE.setText(self.Watch.platform)
                self.SimOperator_LE.setText(self.Watch.sim_operator)
        except Exception:
            self.mylog.error(sys.exc_info())

    def open_watch_dial_ui(self):
        '''
        启动拨号界面
        :return:
        '''
        command = "adb shell am start -n com.xtc.dial/.module.dial.view.activity.DialActivity"
        cmd_run_show_no_return(control=self.result_TE,show_msg="启动拨号界面 ",command=command)

    def open_change_env_ui(self):
        '''
        环境切换界面
        :return:
        '''
        command = "adb shell am start -a com.xtc.i3launcher.ACTION.ConfigActivity"
        cmd_run_show_no_return(control=self.result_TE,show_msg="启动环境切换界面 ",command=command)

    def open_adb_ui(self):
        '''
        ADB界面
        :return:
        '''
        command = "adb shell am start -n com.xtc.selftest/.ui.DebugActivity"
        cmd_run_show_no_return(control=self.result_TE,show_msg="启动ADB界面 ",command=command)

    def open_selfcheck_ui(self):
        '''
        自检界面
        :return:
        '''
        command = "adb shell am start -n com.xtc.selftest/.ui.ControllerActivity"
        cmd_run_show_no_return(control=self.result_TE,show_msg="启动自检界面 ",command=command)

    def watch_reboot(self):
        '''
        手表重启
        :return:
        '''
        reply = QMessageBox.warning(self,"Warnning",
                                         self.tr("确认手表重启？"),
                                         QMessageBox.Yes|QMessageBox.No,
                                         QMessageBox.No)

        if reply == QMessageBox.Yes:
            command = "adb reboot"
            cmd_run_show_no_return(control=self.result_TE, show_msg="手表重启 ", command=command)

    def watch_reboot_edl(self):
        '''
        手表强制重启
        :return:
        '''
        reply = QMessageBox.warning(self,"Warnning",
                                         self.tr("确认手表强制重启？"),
                                         QMessageBox.Yes|QMessageBox.No,
                                         QMessageBox.No)

        if reply == QMessageBox.Yes:
            command = "adb reboot edl"
            cmd_run_show_no_return(control=self.result_TE, show_msg="手表强制重启 ", command=command)

    def get_watch_launcher(self):
        '''
        获取手表launcher
        :return:
        '''
        command = 'adb shell dumpsys package com.xtc.i3launcher | findstr  "versionName"'
        cmd_run_show_with_return(control=self.result_TE, show_msg="获取手表launcher ", command=command)

    def get_watch_battery(self):
        '''
        获取手表电量信息
        :return:
        '''
        command = 'adb shell dumpsys battery'
        cmd_run_show_with_return(control=self.result_TE, show_msg="获取手表电量信息 ", command=command)

    def get_watch_prop(self):
        '''
        获取手表prop信息
        :return:
        '''
        command = 'adb shell getprop'
        cmd_run_show_with_return(control=self.result_TE, show_msg="获取手表prop信息 ", command=command)

    def get_watch_packages(self):
        '''
        获取手表应用信息
        :return:
        '''
        command = 'adb shell pm list packages'
        cmd_run_show_with_return(control=self.result_TE, show_msg="获取手表应用信息 ", command=command)

    def excute_input_cmd(self,cmd):
        '''
        执行输入CMD命令
        :return:
        '''
        command = cmd
        cmd_run_show_with_return(control=self.result_TE, show_msg="执行输入CMD命令 ", command=command)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    widget = MainWindows()
    widget.show()
    widget.mylog.debug("启动应用")
    sys.exit(app.exec_())